package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.AliyunSmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;


@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 利用短信平台发送验证码给手机
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){

        String phone = user.getPhone();

        if (StrUtil.isNotEmpty(phone)) {
            //随机生成6位数密码
            String code = RandomUtil.randomNumbers(6);
            System.out.println(code);
            //利用工具类发送短信验证码
//            AliyunSmsUtil.sendSms(phone,code);
            //保存验证码至session
            session.setAttribute(phone,code);

            return R.success("发送验证码成功");
        }

        return R.error("验证码发送失败");
    }


    /**
     * 用户输入验证码登录
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> user, HttpSession session){
        String phone = user.get("phone");
        String code = user.get("code");
        //从session中通过电话号获取验证码
        String realCode = (String) session.getAttribute(phone);
        //判断验证码是否存在,如果验证码相同则登录成功
        if (code.equals(realCode)){
            //判断手机号是否存在于用户表中
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone,phone);
            User one = userService.getOne(qw);
            if (one!=null){
                //说明不是新用户,存在数据
                session.removeAttribute(phone);
                session.setAttribute("user",one.getId());
                return R.success("验证码正确,登录成功");
            }else{
                //没有记录,新用户登录,添加数据至用户表中
                User newUser = new User();
                newUser.setPhone(phone);
                userService.save(newUser);
                LambdaQueryWrapper<User> qw1 = new LambdaQueryWrapper<>();
                qw1.eq(User::getPhone,phone);
                User user1 = userService.getOne(qw1);
                session.setAttribute("user",user1.getId());
                session.removeAttribute(phone);
                return R.success("验证码正确,新用户登录成功");
            }
        }
        return R.error("验证码错误,登录失败");
    }


    /**
     * 用户退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R loginOut(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出登录成功");
    }
}
